package com.jinzhi.jzapi.common.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.api.exception.IFastApiException;
import com.jinzhi.api.pojo.vo.TokenVO;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.type.ApiEnumError;
import com.jinzhi.common.utils.*;
import com.jinzhi.jzapi.certificate.pojo.MyExpertsVo;
import com.jinzhi.jzapi.certificate.pojo.MyOrgRolesVo;
import com.jinzhi.jzapi.certificate.pojo.MyResultsVo;
import com.jinzhi.jzapi.certificate.pojo.MySignUpListVo;
import com.jinzhi.jzapi.utils.DataEnum;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.sms.support.SmsManager;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.domain.UserRoleDO;
import com.jinzhi.sys.service.UserRoleService;
import com.jinzhi.sys.service.UserService;
import com.jinzhi.wxmp.domain.MpConfigDO;
import com.jinzhi.wxmp.service.MpConfigService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.jinzhi.api.util.TokenTag.TOKEN_TAG;

@Slf4j
@RestController
@RequestMapping("/jzApi/user")
public class ApiUserController extends BaseController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private SmsManager smsSerevice;
    @Autowired
    private MpConfigService mpConfigService;
    @Autowired
    private StuSignUpService stuSignUpService;
    @Autowired
    private OrganizationRolesService organizationRolesService;
    @Autowired
    private OrganizationNewsService organizationNewsService;
    @Autowired
    private ExpertsService expertsService;
    @Autowired
    private ExaminationResultsService examinationResultsService;
    @Autowired
    private CertificationBatchService certificationBatchService;
    @Autowired
    private CertificateNewsService certificateNewsService;
    @Autowired
    private CertificateProfileService certificateProfileService;
    @Autowired
    private ExaminationBatchService examinationBatchService;
    @Autowired
    private ExamineeGroupService examineeGroupService;
    @Autowired
    private MsgService msgService;
    @Autowired
    private TrainingCertificatesService trainingCertificatesService;
     @Autowired
    private CoursesService coursesService;
    @Autowired
    private MsgTemplateService msgTemplateService;
    @Autowired
    private ResumesService resumesService;
    @Autowired
    private MessageplatfromService messageplatfromService;
    @Autowired
    private InfoStoreService infoStoreService;
    @Autowired
    private InfoCollectService infoCollectService;

    @Autowired
    private TrainInfoService trainInfoService;
    private static final String T_REG_SMS_PREFIX = "TRAINING_REG_";//培训端
    private static final String C_REG_SMS_PREFIX = "CERTIFICATE_REG_";//证书端
    private static final String O_REG_SMS_PREFIX = "ORTHER_REG_";//其他端

    //授权（必填）
    String grant_type = DataEnum.wx_grant_type.getValue();

    //微信url
    String wx_url = DataEnum.wx_authorization_url.getValue();


    /**
     * api小程序端-登录
     *
     * @Description: 微信小程序之微信授权登录，参数： 微信小程序id，密文，向量，登录凭证
     * @Param: [wxId, encryptedData, iv, code]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-02-27
     */
    @PostMapping("/login")
    @Log("api小程序端-登录")
    @ApiOperation(value = "api小程序端-登录", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    public ApiResult<?> token(Integer wxId, String encryptedData, String iv, String code) {
        if (wxId == null || wxId == 0) {
            return ApiResult.lack("wxAppId");
        }
        //登录凭证不能为空
        if (StringUtils.isBlank(code)) {
            return ApiResult.lack("code");
        }
        if (StringUtils.isBlank(encryptedData)) {
            return ApiResult.lack("encryptedData");
        }
        if (StringUtils.isBlank(iv)) {
            return ApiResult.lack("iv");
        }
        MpConfigDO mpConfigDO = mpConfigService.selectById(wxId);
        if (null == mpConfigDO) {
            throw new IFastApiException(ApiEnumError.getConfFail.getCodeStr());
        }
        /////////////// 1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid ////////////////
        //请求参数
        String params = "appid=" + mpConfigDO.getAppId() + "&secret=" + mpConfigDO.getAppSecret() + "&js_code=" + code + "&grant_type=" + grant_type;
        //发送请求
        String sr = HttpRequest.sendGet(wx_url, params);
        //解析相应内容（转换成json对象）
        JSONObject json = JSONObject.parseObject(sr);
        String errcode = null;
        if (null != json.get("errcode")) {
            errcode = json.get("errcode").toString();
        }
        if (StringUtils.isNotBlank(errcode)) {
            String errmsg = json.getString("errmsg");
            return ApiResult.build(ApiEnumError.wxThrowFail.getCode(), "微信错误码：" + errcode + "\n" + "微信错误信息：" + errmsg);
        }
        //获取会话密钥（session_key）
        String session_key = json.getString("session_key");
        //用户的唯一标识（openid）
        String openid = json.getString("openid");
        Map<String, Object> map = new HashMap<>();
        try {
            String result = AesCbcUtil.decrypt(encryptedData, session_key, iv, "UTF-8");
            JSONObject object = JSONObject.parseObject(result);
            // 拿到手机号码
            String mobile = object.getString("phoneNumber");
            if (mobile != null) {
                /////////////// 2、根据手机号码查询判断用户是否存在 ////////////////
                log.info("openId:{}", openid);
                UserDO userDO = new UserDO();
                UserDO userDOS = userService.findOneByKv("mobile", mobile);
                if (userDOS != null) {
                    userDO = userDOS;
                    List<Long> roleIds = userRoleService.listRoleId(userDOS.getId());
                    if (roleIds != null && roleIds.size() > 0) {
                        userDOS.setroleIds(roleIds);
                    } else {
                        List<Long> list = new ArrayList<>();
                        list.add(56L);
                        userDOS.setroleIds(list);
                    }

                    if (wxId.equals(101)) {
                        userDOS.setCerOpenId(openid);//证书小程序openId
                    } else if (wxId.equals(102)) {
                        userDOS.setTraOpenId(openid);//培训小程序openId
                    }

                    userService.updateById(userDOS);
                } else {
                    userDO.setUsername(mobile);//默认存入手机号码
                    userDO.setWxId(wxId);
                    if (wxId.equals(101)) {
                        userDO.setCerOpenId(openid);//证书小程序openId
                    } else if (wxId.equals(102)) {
                        userDO.setTraOpenId(openid);//培训小程序openId
                    }
                    userDO.setMobile(mobile);
                    userDO.setType(0);//默认个人会员
                    userDO.setMoney(BigDecimal.valueOf(0.0));//默认0元
                    userDO.setGmtCreate(new Date());
                    userDO.setGmtModified(userDO.getGmtCreate());
                    userDO.setStatus(1);//默认正常
                    userDO.setSex(0L);//默认未知

                    List<Long> list = new ArrayList<>();
                    list.add(56L);
                    userDO.setroleIds(list);

                    userService.insertNoPW(userDO);
                }

                /////////////// 3、生成自定义登录态(jwt token) ////////////////
                //生成,根据openid
                TokenVO token = userService.getToken(mobile);

                ///////////////  4、将生成自定义登录态与session_key、openid进行关联 ////////////////
                Map cache = new HashMap();
                cache.put("session_key", session_key);
                cache.put("mobile", mobile);
                EhCacheUtil.put(token.getToken(), cache);

                /////////////// 5、返回自定义登录态token + 用户信息////////////////
                map.put("isOpenId",true);//20200701 pjr新增isOpenId
                map.put("token", token.getToken());
                map.put("userId", userDO.getId());
                map.put("userName", userDO.getUsername());
                map.put("headPortrait", userDO.getHeadPortrait());
            } else {
                return ApiResult.fail(ApiEnumError.USER_NOT_MOBILE.getCodeStr());
            }
        } catch (Exception e) {
            return ApiResult.fail(e.getMessage());
        }

        return ApiResult.success(map);
    }


    /**
     * api小程序端-手机号登录
     *
     * @Description: 微信小程序手机号验证码、用户名或手机号密码登录，参数： 小程序id，用户名或手机号码，验证码，登录密码，登录类型  password密码登录  code验证码登录 name
     * @Param: [wxId, account, code, passWord, type]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-02-27
     */
    @PostMapping("/mobileLogin")
    @Log("api小程序端-手机号登录")
    @ApiOperation(value = "api小程序端-手机号登录", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> mobileLogin(Integer wxId, String account, String code, String passWord, String type) {
        //第一布验证登录形式，是密码登录还是验证码登录
        if (type.equals("password")) {//密码登录
            if (StringUtils.isBlank(passWord)) {
                return ApiResult.lack("password");
            } else {
                //第二步，根据账户获取用户信息
                UserDO userDOS = userService.findOneByKv("mobile", account);
                if (userDOS != null) {//查到了用户信息
                    //第三步，验证登录信息
                    UsernamePasswordToken token = new UsernamePasswordToken(userDOS.getUsername(), passWord);
//                    token.setRememberMe(false);//记住我是可选项，但只有会话缓存到redis等持久存储才能真正记住
                    Subject subject = SecurityUtils.getSubject();
                    try {
                        subject.login(token);
                        //第四步，根据手机号码生成自定义登录态
                        TokenVO returnToken = userService.getToken(userDOS.getMobile());

                        //第五步，将生成的登录态和手机号码关联，并存到缓存中
                        Map cache = new HashMap();
                        cache.put("mobile", userDOS.getMobile());
                        EhCacheUtil.put(returnToken.getToken(), cache);

                        //第六步，返回登录态和用户信息
                        Map<String, Object> map = new HashMap<>();
                        //20200701 pjr新增isOpenId
                        if (wxId.equals(101)) {
                            if (StringUtils.isBlank(userDOS.getCerOpenId())) {
                                map.put("isOpenId", false);//没有OpenId
                            } else {
                                map.put("isOpenId", true);//有OpenId
                            }
                        } else if (wxId.equals(102)) {
                            if (StringUtils.isBlank(userDOS.getTraOpenId())) {
                                map.put("isOpenId", false);
                            } else {
                                map.put("isOpenId", true);
                            }
                        }
                        map.put("token", returnToken.getToken());
                        map.put("userId", userDOS.getId());
                        map.put("userName", userDOS.getUsername());
                        map.put("headPortrait", userDOS.getHeadPortrait());
                        return ApiResult.success(map);
                    } catch (AuthenticationException e) {
                        return ApiResult.build(ApiEnumError.USERNAME_OR_PASSWORD.getCode(), ApiEnumError.USERNAME_OR_PASSWORD.getMsg());
                    }
                } else {//没有查到用户信息
                    //第二步，根据用户名再查一次，如没有，则说明没有注册
                    UserDO userDOS1 = userService.findOneByKv("username", account);
                    if (userDOS1 != null) {
                        //第三步，验证登录信息
                        UsernamePasswordToken token = new UsernamePasswordToken(userDOS1.getUsername(), passWord);
//                        token.setRememberMe(false);//记住我是可选项，但只有会话缓存到redis等持久存储才能真正记住
                        Subject subject = SecurityUtils.getSubject();
                        try {
                            subject.login(token);
                            //第四步，根据手机号码生成自定义登录态
                            TokenVO returnToken = userService.getToken(userDOS1.getMobile());

                            //第五步，将生成的登录态和手机号码关联
                            Map cache = new HashMap();
                            cache.put("mobile", userDOS1.getMobile());
                            EhCacheUtil.put(returnToken.getToken(), cache);

                            //第六步，返回登录态和用户信息
                            //20200701 pjr新增isOpenId
                            Map<String, Object> map = new HashMap<>();
                             if (wxId.equals(101)) {
                                 if(StringUtils.isBlank(userDOS1.getCerOpenId())){
                                    map.put("isOpenId",false);//没有OpenId
                                 }else{
                                    map.put("isOpenId",true);//有OpenId
                                 }
                            } else if (wxId.equals(102)) {
                                 if(StringUtils.isBlank(userDOS1.getTraOpenId())){
                                    map.put("isOpenId",false);
                                 }else{
                                    map.put("isOpenId",true);
                                 }
                            }
                            map.put("token", returnToken.getToken());
                            map.put("userId", userDOS1.getId());
                            map.put("userName", userDOS1.getUsername());
                            map.put("headPortrait", userDOS1.getHeadPortrait());
                            return ApiResult.success(map);
                        } catch (AuthenticationException e) {
                            return ApiResult.build(ApiEnumError.USERNAME_OR_PASSWORD.getCode(), ApiEnumError.USERNAME_OR_PASSWORD.getMsg());
                        }
                    } else {
                        return ApiResult.build(ApiEnumError.WEBRGE_OR_CODE.getCode(), ApiEnumError.WEBRGE_OR_CODE.getMsg());
                    }
                }
            }
        } else if (type.equals("code")) {//验证码登录
            if (StringUtils.isBlank(code)) {
                return ApiResult.lack("code");
            } else {
                //第二步，判断验证码
                try {
                    if (wxId.equals(101)) {
                        smsSerevice.verify(C_REG_SMS_PREFIX, account, code);
                    } else if (wxId.equals(102)) {
                        smsSerevice.verify(T_REG_SMS_PREFIX, account, code);
                    } else {
                        smsSerevice.verify(O_REG_SMS_PREFIX, account, code);
                    }
                } catch (Exception e) {
                    return ApiResult.build(ApiEnumError.apiSmsCodeInvalid.getCode(), ApiEnumError.apiSmsCodeInvalid.getMsg());
                }
                //第三步，根据手机号码获取用户信息并判断，如没有则新建，如果则返回信息
                UserDO userDOS = userService.findOneByKv("mobile", account);
                if (userDOS == null) {
                    UserDO userDO = new UserDO();
                    userDO.setUsername(account);//默认手机号为新建账号的初始用户名
                    userDO.setWxId(wxId);
                    userDO.setMobile(account);
                    userDO.setType(0);//默认个人会员
                    userDO.setMoney(BigDecimal.valueOf(0.0));//默认0元
                    userDO.setGmtCreate(new Date());
                    userDO.setGmtModified(userDO.getGmtCreate());
                    userDO.setStatus(1);//默认正常
                    userDO.setSex(0L);//默认未知

                    List<Long> list = new ArrayList<>();
                    list.add(56L);
                    userDO.setroleIds(list);

                    userService.insertNoPW(userDO);

                    userDOS = userDO;
                }

                //第四步，根据手机号码生成自定义登录态
                TokenVO returnToken = userService.getToken(account);

                //第五步，将生成的登录态和手机号码关联
                Map cache = new HashMap();
                cache.put("mobile", account);
                EhCacheUtil.put(returnToken.getToken(), cache);

                //第六步，返回登录态和用户信息
                Map<String, Object> map = new HashMap<>();
                //20200701 pjr新增isOpenId
                if (wxId.equals(101)) {
                    if (StringUtils.isBlank(userDOS.getCerOpenId())) {
                        map.put("isOpenId", false);//没有OpenId
                    } else {
                        map.put("isOpenId", true);//有OpenId
                    }
                } else if (wxId.equals(102)) {
                    if (StringUtils.isBlank(userDOS.getTraOpenId())) {
                        map.put("isOpenId", false);
                    } else {
                        map.put("isOpenId", true);
                    }
                }
                map.put("token", returnToken.getToken());
                map.put("userId", userDOS.getId());
                map.put("userName", userDOS.getUsername());
                map.put("headPortrait", userDOS.getHeadPortrait());
                return ApiResult.success(map);

            }
        } else {
            return ApiResult.fail();
        }
    }


    /**
     * api小程序端-发送注册验证短信
     *
     * @Description: 调取短信平台发送短信，参数： 微信端口id，手机号码
     * @Param: [wxId, mobile]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-02-27
     */
    @PostMapping("/sendSms")
    @Log("api小程序端-发送注册验证短信")
    @ApiOperation(value = "api小程序端-发送注册验证短信", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult<?> sendSms(Integer wxId, String mobile) {
        //第一步验证手机号格式
        if (StringUtils.isBlank(mobile)) {
            return ApiResult.lack("mobile");
        }
        if (!ValidUtils.isMobile(mobile)) {
            return ApiResult.format("mobile");
        }

        //第二步发送短信，错误信息由方法直接返回
        Object smsDemo = EhCacheUtil.get("登录短信验证");
        if(smsDemo == null){
            MessageplatfromDO messageplatfromDO = messageplatfromService.findOneByKv("登录短信验证");
            if(messageplatfromDO != null){
                EhCacheUtil.put("登录短信验证",messageplatfromDO.getSmsDemo());
                if (wxId.equals(101)) {
                    smsSerevice.send(C_REG_SMS_PREFIX, mobile,messageplatfromDO.getSmsDemo());
                } else if (wxId.equals(102)) {
                    smsSerevice.send(T_REG_SMS_PREFIX, mobile,messageplatfromDO.getSmsDemo());
                } else {
                    smsSerevice.send(O_REG_SMS_PREFIX, mobile,messageplatfromDO.getSmsDemo());
                }
            }else{
                return ApiResult.fail("短信模板错误，请联系管理员！");
            }
        }else{
            if (wxId.equals(101)) {
                smsSerevice.send(C_REG_SMS_PREFIX, mobile,(String) smsDemo);
            } else if (wxId.equals(102)) {
                smsSerevice.send(T_REG_SMS_PREFIX, mobile,(String) smsDemo);
            } else {
                smsSerevice.send(O_REG_SMS_PREFIX, mobile,(String) smsDemo);
            }
        }

        return ApiResult.success("发送成功");
    }


    /**
     * api小程序端-校验验证码
     *
     * @Description: 校验短信验证码，验证成功后验证码失效，备用方法；参数：微信端口id，手机号码，验证码
     * @Param: [wxId, mobile, code]
     * @return: com.jinzhi.common.utils.ApiResult
     * @Author: kl
     * @Date: 2020-02-27
     */
    @PostMapping("/verify")
    @Log("api小程序端-校验验证码")
    @ApiOperation(value = "api小程序端-校验验证码", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiResult verify(Integer wxId, String mobile, String code) {
        //错误信息由方法直接返回
        if (wxId.equals(101)) {
            smsSerevice.verify(C_REG_SMS_PREFIX, mobile, code);
        } else if (wxId.equals(102)) {
            smsSerevice.verify(T_REG_SMS_PREFIX, mobile, code);
        } else {
            smsSerevice.verify(O_REG_SMS_PREFIX, mobile, code);
        }
        return ApiResult.success("校验成功");
    }


    /**
     * api小程序端-获取用户信息
     *
     * @Description: 小程序登录后，获取用户信息；参数：token令牌
     * @Param: [token]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-04
     */
    @GetMapping("/selUserDetail")
    @Log("api客户端-获取用户信息")
    @ApiOperation("api客户端-获取用户信息")
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> selUserDetail(@RequestHeader(value = TOKEN_TAG, required = false) String token) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        } else {
            user.setRoleNameList(getRoleNamesToken(user.getId()));
            return ApiResult.success(user);
        }
    }


    /**
     * 查询机构列表信息
     *
     * @Description:
     * @Author: xzy
     * @Date: 2020-03-04
     */
    @PostMapping("/selmechanismList")
    @Log("查询机构信息")
    @ApiOperation("查询机构信息")
    public ApiResult<?> selmechanismList() {

        return ApiResult.success( organizationNewsService.selmechanismList());
    }

    /**
     * api小程序端-我的报名记录接口
     *
     * @Description: 小程序登录后，获取用户报名记录信息；参数：验证token，页码，显示数
     * @Param: [token, current, number]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-05
     */
    @GetMapping("/selMySignUpList")
    @Log("api客户端-我的报名记录接口")
    @ApiOperation("api客户端-我的报名记录接口")
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> selMySignUpList(@RequestHeader(value = TOKEN_TAG, required = false) String token, String current, String number) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }

        Page<MySignUpListVo> page = stuSignUpService.selByUserId(Integer.parseInt(current), Integer.parseInt(number), user.getId());
        return ApiResult.success(page);
    }


    /**
     * api客户端-我的准考证信息接口
     * <p>
     *
     * @Description: 小程序登录后，获取用户准考证信息；参数：token令牌，报名记录id
     * @Param: [token, id]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-23
     */
    @GetMapping("/selMyExaminationList")
    @Log("api客户端-我的准考证信息接口")
    @ApiOperation("api客户端-我的准考证信息接口")
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> selMyExaminationList(@RequestHeader(value = TOKEN_TAG, required = false) String token, String id) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }

        Map map = new HashMap();
        StuSignUpDO stuSignUpDO = stuSignUpService.selectById(Long.parseLong(id));
        if (stuSignUpDO != null) {
            map.put("name", stuSignUpDO.getName());//考生姓名
            map.put("ticketNumber", stuSignUpDO.getTicketNumber());//考号
            map.put("idNumber", stuSignUpDO.getIdNumber());//身份证号码
            map.put("photo", stuSignUpDO.getPhoto());//考生照片
            if (user.getSex() == 1) {
                map.put("sex", "男");//考生性别
            } else if (user.getSex() == 2) {
                map.put("sex", "女");//考生性别
            } else {
                map.put("sex", "未知");//考生性别
            }

            OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(stuSignUpDO.getOrgId());
            if (organizationNewsDO != null) {
                map.put("orgName", organizationNewsDO.getName());//考点名称
                map.put("address", organizationNewsDO.getAddress());//考点地址
            } else {
                map.put("orgName", "");//考点名称
                map.put("address", "");//考点地址
            }

            CertificationBatchDO certificationBatchDO = certificationBatchService.selectById(stuSignUpDO.getCbatchId());
            if (certificationBatchDO != null) {
                //准考证名
                map.put("cName", certificationBatchDO.getName());
                //证书概况
                CertificateProfileDO certificateProfileDO = certificateProfileService.selectById(certificationBatchDO.getProfileId());
                if (certificateProfileDO != null) {
                    map.put("profileName", certificateProfileDO.getName());//证书名称
                } else {
                    map.put("profileName", "无");//证书名称
                }
                //证书信息
                CertificateNewsDO certificateNewsDO = certificateNewsService.selectById(certificationBatchDO.getNewsId());
                if (certificateNewsDO != null) {
                    map.put("grade", certificateNewsDO.getGrade());//证书名称
                } else {
                    map.put("grade", "无");//证书名称
                }

                //考试科目
                List<ExaminationBatchDO> examinationBatchDOs = examinationBatchService.findByKv("cbatch_id", certificationBatchDO.getId());
                if (examinationBatchDOs != null && examinationBatchDOs.size() > 0) {
                    List list = new ArrayList();

                    for (ExaminationBatchDO examinationBatchDO : examinationBatchDOs) {
                        Map map1 = new HashMap();
                        map1.put("examinType", examinationBatchDO.getType());//考试类型
                        map1.put("ebatchName", examinationBatchDO.getName());//考试名称

                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                        SimpleDateFormat formatter1 = new SimpleDateFormat("HH:mm");
                        String yearTime = formatter.format(examinationBatchDO.getStartTime());
                        String startTime = formatter1.format(examinationBatchDO.getStartTime());
                        String endTime = formatter1.format(examinationBatchDO.getEndTime());
                        map1.put("examinTime", yearTime + " " + startTime + "-" + endTime);//考试时间

                        if (examinationBatchDO.getType() == 0) {
                            //考生编号格式：职业技能等级标准代码（3位） +证书等级代码（2位）+年份（2位）+考点序列号（3位）+考场号（2位）+座位号（2位）
                            String roomNumber = stuSignUpDO.getTicketNumber().substring(stuSignUpDO.getTicketNumber().length() - 4, stuSignUpDO.getTicketNumber().length() - 2);
                            String seatNum = stuSignUpDO.getTicketNumber().substring(stuSignUpDO.getTicketNumber().length() - 2);
                            map1.put("roomNumber", roomNumber);//考场号
                            map1.put("seatNum", seatNum);//座位号
                            map1.put("type", "理论考试");
                            list.add(map1);
                        } else {
                            ExamineeGroupDO examineeGroupDO = examineeGroupService
                                    .findOneByKv("stu_sign_id",stuSignUpDO.getId(),"org_id",organizationNewsDO.getId(),"ebatch_id",examinationBatchDO.getId());
                            if(examineeGroupDO != null){
                                map1.put("roomNumber", examineeGroupDO.getExaminRoomNum());//考场号
                                map1.put("seatNum", examineeGroupDO.getGroupNum()+"组"+examineeGroupDO.getStationNum()+"号工位");//座位号
                            }else{
                                map1.put("roomNumber", "无");//考场号
                                map1.put("seatNum", "无");//座位号
                            }
                            map1.put("type", "技能考试");
                            list.add(map1);
                        }

                    }
                    map.put("ebatchs", list);
                } else {
                    map.put("ebatchs", "");
                }
            } else {
                map.put("profileName", "无");//证书名称
                map.put("grade", "无");//证书名称
            }
        }

        return ApiResult.success(map);
    }

    /**
     * api小程序端-我的成绩接口
     *
     * @Description: 小程序登录后，查询用户成绩接口；参数：token令牌，页码，显示数
     * @Param: [token, current, number]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-05
     */
    @GetMapping("/selAchievementList")
    @Log("api客户端-我的成绩接口")
    @ApiOperation("api客户端-我的成绩接口")
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> selAchievementList(@RequestHeader(value = TOKEN_TAG, required = false) String token, String current, String number) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }
        Map map = new HashMap();
        map.put("userId", user.getId());
        Page<MyResultsVo> page = examinationResultsService.selByUserId(map, Integer.parseInt(current), Integer.parseInt(number));
        return ApiResult.success(page);
    }


    /**
     * api小程序端-我的站点申请记录接口
     *
     * @Description: 小程序登录后，查询站点申请记录；参数：token令牌，页码，显示数
     * @Param: [token, current, number]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-05
     */
    @GetMapping("/selMyExaminationPointList")
    @Log("api客户端-我的站点申请记录接口")
    @ApiOperation("api客户端-我的站点申请记录接口")
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> selMyExaminationPointList(@RequestHeader(value = TOKEN_TAG, required = false) String token, String current, String number) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }

        Page<MyOrgRolesVo> page = organizationRolesService.selByUserId(Integer.parseInt(current), Integer.parseInt(number), user.getId());
        return ApiResult.success(page);
    }

    /**
     * api小程序端-我的培训站点站点申请记录接口
     *
     * @Description: 小程序登录后，查询站点申请记录；参数：token令牌，页码，显示数
     * @Param: [token, current, number]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-05
     */
    @GetMapping("/selMyExaminationPointListPx")
    @Log("api客户端-我的培训站点申请记录接口")
    @ApiOperation("api客户端-我的培训站点申请记录接口")
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> selMyExaminationPointListPx(@RequestHeader(value = TOKEN_TAG, required = false) String token, String current, String number) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }

        Page<TrainInfoDO> page1 = trainInfoService.selectPage(getPage(TrainInfoDO.class),
                trainInfoService.convertToEntityWrapper().like("create_user",user.getId().toString()).orderBy("id", false));

        return ApiResult.success(page1);
    }

    /**
     * api小程序端-我的培训站点站点申请记录接口
     *
     * @Description: 小程序登录后，查询站点申请记录；参数：token令牌，页码，显示数
     * @Param: [token, current, number]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-05
     */
    @GetMapping("/selMyInfoList")
    @Log("api客户端-我的表单提交记录接口")
    @ApiOperation("api客户端-我的表单提交记录接口")
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> selMyInfoList(@RequestHeader(value = TOKEN_TAG, required = false) String token, String current, String number) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }

        Page<InfoCollectDO> page1 = infoCollectService.selectPage(getPage(InfoCollectDO.class),
                infoCollectService.convertToEntityWrapper().like("user_id",user.getId().toString()).orderBy("id", false));
        for (InfoCollectDO info : page1.getRecords()) {
            info.setInfoStoreName(infoStoreService.selectById(info.getInfoStoreId()).getName());
        }

        return ApiResult.success(page1);
    }

    /**
     * api小程序端-我的专家申请记录接口
     *
     * @Description: 小程序登录后，查询专家申请记录；参数：token令牌，页码，显示数
     * @Param: [token, current, number]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-05
     */
    @GetMapping("/selMyExpertsList")
    @Log("api客户端-我的专家申请记录接口")
    @ApiOperation("api客户端-我的专家申请记录接口")
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> selMyExpertsList(@RequestHeader(value = TOKEN_TAG, required = false) String token, String current, String number) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }

        Page<MyExpertsVo> page = expertsService.selByUserId(Integer.parseInt(current), Integer.parseInt(number), user.getId());
        return ApiResult.success(page);
    }


    /**
     * api小程序端-个人中心—修改个人资料接口
     *
     * @Description: 用户修改个人资料，编辑提交；
     * 参数：token令牌，照片，用户名，真实姓名，性别，身份证号码，手机号，所属机构名称，出生年月，民族，学历，专业，政治面貌，职务职称，qq，邮箱，学习、工作经历，现居住地-申请表中通讯地址组合传递,省份，市，区
     * @Param: [token, img, username, name, sex, idNumber, mobile, orgName, dateOfBirth, nation, education, major, politicalAffiliation,
     * officialCapacity, QQ, email, experience, liveAddress,province，city，district]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-13
     */
    @PostMapping("/editUserDetail")
    @Log("api客户端-个人中心—修改个人资料接口")
    @ApiOperation("api客户端-个人中心—修改个人资料接口")
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> editUserDetail(@RequestHeader(value = TOKEN_TAG, required = false) String token, String username, String name, String sex, String idNumber,
                                       String mobile, String orgName, String dateOfBirth, String nation, String education, String major, String politicalAffiliation, String officialCapacity, String QQ, String email,
                                       String experience, String liveAddress, String province, String city, String district , String lastEdit) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }
        Map map = new HashMap();
        MsgTemplateDO msg = msgTemplateService.findOneByKv("type" , 0, "temp_ip" , lastEdit);
        if (msg != null){
            map.put("tempId" , msg.getCode());
        }else {
            map.put("tempId" , null);
        }

        //2020-04-10 kl ： 如果用户名修改，判断用户名是否存在，如存在则提示用户名已存在；
        if (!username.equals(user.getUsername())) {
            UserDO users = userService.findOneByKv("username", username);
            if (users != null) {
                return ApiResult.build(ApiEnumError.USERNAMEEXISTED.getCode(), ApiEnumError.USERNAMEEXISTED.getMsg());
            }
        }
        //2020-09-04 kl ： 如果手机号码修改，判断手机号码是否存在，如存在则提示手机号码已存在；
        if (!mobile.equals(user.getMobile())) {
            UserDO users = userService.findOneByKv("mobile", mobile);
            if (users != null) {
                return ApiResult.build(ApiEnumError.mobileAlreadyReg.getCode(), ApiEnumError.mobileAlreadyReg.getMsg());
            }
        }

        user.setUsername(username);
        user.setName(name);
        user.setSex(Long.parseLong(sex));
        user.setIdNumber(idNumber);
        user.setMobile(mobile);
        user.setNation(nation);
        user.setEducation(education);
        user.setMajor(major);
        user.setPoliticalAffiliation(politicalAffiliation);
        user.setOfficialCapacity(officialCapacity);
        user.setQQ(QQ);
        user.setEmail(email);
        user.setExperience(experience);
        user.setLiveAddress(liveAddress);
        user.setOrgName(orgName);
        user.setDistrict(district);//地区
        user.setCity(city);//市
        user.setProvince(province);//省份
        user.setDateOfBirth(dateOfBirth);//出生年月
        user.setLastEdit(Integer.parseInt(lastEdit));

        // 查询判断机构是否在系统内存在： 如不存在，则只在用户表中存入机构信息； 如存在，则存入机构id
        EntityWrapper<OrganizationNewsDO> entityWrapper = new EntityWrapper<>();
        entityWrapper.like("name", orgName);
        List<OrganizationNewsDO> organizationNewsDOList = organizationNewsService.selectList(entityWrapper);
        if (CollectionUtils.isEmpty(organizationNewsDOList)) { // 无机构，则机构信息错误
            return ApiResult.build(ApiEnumError.orgsErr.getCode(), ApiEnumError.NoorgsErr.getMsg());
        } else if (organizationNewsDOList.size() > 1) { // 多机构，则机构信息不全
            return ApiResult
                    .build(ApiEnumError.orgsIncompleteInfo.getCode(), ApiEnumError.orgsIncompleteInfo.getMsg());
        } else {
            user.setOrgId(organizationNewsDOList.get(0).getId());
        }


        //编辑用户信息时，记得添加角色信息，否则或导致后期角色错误
        List<Long> roleIds = new ArrayList<>();

        List<UserRoleDO> userRoleDO = userRoleService.findByKv("userId", user.getId());
        if (userRoleDO != null && userRoleDO.size() > 0) {
            for (int i = 0; i < userRoleDO.size(); i++) {
                roleIds.add(userRoleDO.get(i).getRoleId());
            }
        } else {
            roleIds.add(56L);
        }

        user.setroleIds(roleIds);
        user.setState(1);

        boolean b = userService.updateById(user);
        if (b) {
            //todo 考生信息、专家表、简历表的信息编辑同步
            return ApiResult.success(map);
        } else {
            return ApiResult.build(ApiEnumError.EDITERR.getCode(), ApiEnumError.EDITERR.getMsg());
        }
    }


    /**
     * 门户端-个人中心—修改个人资料接口
     *
     * @Description: 用户修改个人资料，编辑提交；
     * 参数：token令牌，照片，用户名，真实姓名，性别，身份证号码，手机号，所属机构名称，出生年月，民族，学历，专业，政治面貌，职务职称，qq，邮箱，学习、工作经历，现居住地-申请表中通讯地址组合传递,省份，市，区
     * @Param: [token, img, username, name, sex, idNumber, mobile, orgName, dateOfBirth, nation, education, major, politicalAffiliation,
     * officialCapacity, QQ, email, experience, liveAddress,province，city，district]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-13
     */
    @PostMapping("/editUserDetailDoor")
    @Log("api客户端-个人中心—修改个人资料接口")
    @ApiOperation("api客户端-个人中心—修改个人资料接口")
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> editUserDetailDoor(@RequestHeader(value = TOKEN_TAG, required = false) String token, String headPortrait, String username, String name, String sex, String idNumber,
                                           Integer lastEdit, String mobile, String orgName, String dateOfBirth, String nation, String education, String major, String politicalAffiliation, String officialCapacity, String QQ, String email,
                                           String experience, String liveAddress, String province, String city, String district) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }

        //2020-04-10 kl ： 如果用户名修改，判断用户名是否存在，如存在则提示用户名已存在；
        if (!username.equals(user.getUsername())) {
            UserDO users = userService.findOneByKv("username", username);
            if (users != null) {
                return ApiResult.build(ApiEnumError.USERNAMEEXISTED.getCode(), ApiEnumError.USERNAMEEXISTED.getMsg());
            }
        }
        //2020-09-04 kl ： 如果手机号码修改，判断手机号码是否存在，如存在则提示手机号码已存在；
        if (!mobile.equals(user.getMobile())) {
            UserDO users = userService.findOneByKv("mobile", mobile);
            if (users != null) {
                return ApiResult.build(ApiEnumError.mobileAlreadyReg.getCode(), ApiEnumError.mobileAlreadyReg.getMsg());
            }
        }

        user.setHeadPortrait(headPortrait);
        user.setUsername(username);
        user.setName(name);
        user.setSex(Long.parseLong(sex));
        user.setIdNumber(idNumber);
        user.setMobile(mobile);
        user.setNation(nation);
        user.setEducation(education);
        user.setMajor(major);
        user.setPoliticalAffiliation(politicalAffiliation);
        user.setOfficialCapacity(officialCapacity);
        user.setQQ(QQ);
        user.setEmail(email);
        user.setExperience(experience);
        user.setLiveAddress(liveAddress);
        user.setOrgName(orgName);
        user.setDistrict(district);//地区
        user.setCity(city);//市
        user.setProvince(province);//省份
        user.setDateOfBirth(dateOfBirth);//出生年月
        user.setLastEdit(lastEdit);

        // 查询判断机构是否在系统内存在： 如不存在，则只在用户表中存入机构信息； 如存在，则存入机构id
        EntityWrapper<OrganizationNewsDO> entityWrapper = new EntityWrapper<>();
        entityWrapper.like("name", orgName);
        List<OrganizationNewsDO> organizationNewsDOList = organizationNewsService.selectList(entityWrapper);
        if (CollectionUtils.isEmpty(organizationNewsDOList)) { // 无机构，则机构信息错误
            return ApiResult.build(ApiEnumError.orgsErr.getCode(), ApiEnumError.orgsErr.getMsg());
//        } else if (organizationNewsDOList.size() > 1) { // 多机构，则机构信息不全
//            return ApiResult
//                    .build(ApiEnumError.orgsIncompleteInfo.getCode(), ApiEnumError.orgsIncompleteInfo.getMsg());
//        }
        } else {
            user.setOrgId(organizationNewsDOList.get(0).getId());
        }


        //编辑用户信息时，记得添加角色信息，否则或导致后期角色错误
        List<Long> roleIds = new ArrayList<>();

        List<UserRoleDO> userRoleDO = userRoleService.findByKv("userId", user.getId());
        if (userRoleDO != null && userRoleDO.size() > 0) {
            for (int i = 0; i < userRoleDO.size(); i++) {
                roleIds.add(userRoleDO.get(i).getRoleId());
            }
        } else {
            roleIds.add(56L);
        }

        user.setroleIds(roleIds);
        user.setState(1);

        boolean b = userService.updateById(user);
        if (b) {
            //todo 考生信息、专家表、简历表的信息编辑同步
            return ApiResult.success();
        } else {
            return ApiResult.build(ApiEnumError.EDITERR.getCode(), ApiEnumError.EDITERR.getMsg());
        }
    }

    /**
     * api小程序端-个人中心—修改照片接口
     *
     * @Author: pjr
     * @Date: 2020-04-24
     */
    @PostMapping("/editHeadPortrait")
    @Log("api客户端-个人中心—修改照片接口")
    @ApiOperation("api客户端-个人中心—修改照片接口")
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> editHeadPortrait(@RequestHeader(value = TOKEN_TAG, required = false) String token, String img) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }
        user.setHeadPortrait(img);//证件照
        //编辑用户信息时，记得添加角色信息，否则或导致后期角色错误
        List<Long> roleIds = new ArrayList<>();

        List<UserRoleDO> userRoleDO = userRoleService.findByKv("userId", user.getId());
        if (userRoleDO != null && userRoleDO.size() > 0) {
            for (int i = 0; i < userRoleDO.size(); i++) {
                roleIds.add(userRoleDO.get(i).getRoleId());
            }
        } else {
            roleIds.add(56L);
        }

        user.setroleIds(roleIds);
        boolean b = userService.updateById(user);
        if (b) {
            //todo 考生信息、专家表、简历表的信息编辑同步
            return ApiResult.success();
        } else {
            return ApiResult.build(ApiEnumError.EDITERR.getCode(), ApiEnumError.EDITERR.getMsg());
        }
    }


    /**
     * api小程序端-设置登录密码接口
     *
     * @Description: 用户设置登录密码（如为手机验证码注册登录，则没有密码），参数：token令牌，老密码（如果是第一次设置不用输入老密码），新密码
     * @Param: [token, oldPassword, newPassword]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-13
     */
    @PostMapping("/setPassword")
    @Log("api客户端-设置登录密码接口")
    @ApiOperation("api客户端-设置登录密码接口")
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> setPassword(@RequestHeader(value = TOKEN_TAG, required = false) String token, String oldPassword, String newPassword) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }

        List<Long> roleIds = new ArrayList<>();

        if (StringUtils.isNotBlank(user.getPassword())) {
            if (oldPassword != null) {
                if (Objects.equals(PasswdUtils.get(oldPassword, user.getSalt()), user.getPassword())) {
                    String newSalt = UUIDUtils.get();
                    String newPasswd = PasswdUtils.get(newPassword, newSalt);
                    user.setPassword(newPasswd);
                    user.setSalt(newSalt);

                    //编辑用户信息时，记得添加角色信息，否则或导致后期角色错误
                    List<UserRoleDO> userRoleDO = userRoleService.findByKv("userId", user.getId());
                    if (userRoleDO != null && userRoleDO.size() > 0) {
                        for (int i = 0; i < userRoleDO.size(); i++) {
                            roleIds.add(userRoleDO.get(i).getRoleId());
                        }
                    } else {
                        roleIds.add(56L);
                    }

                    user.setroleIds(roleIds);

                    boolean b = userService.updateById(user);
                    if (b) {
                        return ApiResult.success();
                    }
                } else {
                    return ApiResult.build(ApiEnumError.PASSWORDERROR.getCode(), ApiEnumError.PASSWORDERROR.getMsg());
                }
            } else {
                return ApiResult.build(ApiEnumError.PASSWORDFAIL.getCode(), ApiEnumError.PASSWORDFAIL.getMsg());
            }
        } else {
            String salt = UUIDUtils.get();
            String encodePasswd = PasswdUtils.get(newPassword, salt);
            user.setSalt(salt);
            user.setPassword(encodePasswd);

            //编辑用户信息时，记得添加角色信息，否则或导致后期角色错误
            List<UserRoleDO> userRoleDO = userRoleService.findByKv("userId", user.getId());
            if (userRoleDO != null && userRoleDO.size() > 0) {
                for (int i = 0; i < userRoleDO.size(); i++) {
                    roleIds.add(userRoleDO.get(i).getRoleId());
                }
            } else {
                roleIds.add(56L);
            }

            user.setroleIds(roleIds);

            boolean b = userService.updateById(user);
            if (b) {
                return ApiResult.success();
            }
        }

        return ApiResult.fail();
    }

    @Log("小程序端-消息中心列表")
    @GetMapping("/msgListApi")
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    ApiResult<?> msgListApi(@RequestHeader(value = TOKEN_TAG, required = false) String token, int current, int number, String state, String type) {
        UserDO user = this.getClientUser(token);
        Map map = new HashMap();
        map.put("userId", user.getId());
        map.put("state", state);
        map.put("type", type);
        Page<MsgDO> page = msgService.selMsgPage(current, number, map);
        List<MsgDO> list = page.getRecords();
        for (MsgDO msg : list) {
            msg.setUserName(user.getUsername());
            UserDO user1 = userService.selectById(msg.getCreaterId());
            msg.setCreaterName(user1.getUsername());
        }
        page.setRecords(list);
        return ApiResult.success(page);
    }

    @Log("小程序端-消息中心更改状态")
    @GetMapping("/updateStateApi")
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> updateStateApi(@RequestHeader(value = TOKEN_TAG, required = false) String token, Long id) {
        UserDO user = this.getClientUser(token);
        if (user == null) {
            return ApiResult.invalid();
        }
        MsgDO msg = msgService.selectById(id);
        msg.setState(2);
        msgService.updateById(msg);
        return ApiResult.success();
    }

    @Log("小程序端-未读消息条数")
    @GetMapping("/unreadNumApi")
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    ApiResult<?> unreadNumApi(@RequestHeader(value = TOKEN_TAG, required = false) String token, Integer type) {
        UserDO user = this.getClientUser(token);
        if (user == null) {
            return ApiResult.invalid();
        }
        List<MsgDO> msg = msgService.findByKv("state", 0, "userId", user.getId(), "type", type);
        return ApiResult.success(msg.size());
    }

    @Log("查询我的证书")
    @GetMapping("/selMyCer")
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> selMyCer(@RequestHeader(value = TOKEN_TAG, required = false) String token , Integer current , Integer number){

        UserDO user = this.getClientUser(token);
        if (user == null){
            return ApiResult.invalid();
        }

        Page<TrainingCertificatesDO> page = trainingCertificatesService.findPageList(current , number , user.getId());
        List<TrainingCertificatesDO> traList = page.getRecords();

        for (TrainingCertificatesDO training : traList){
            CoursesDO courses = coursesService.selectById(training.getCoursesId());
            if (courses != null){
                training.setCoursesName(courses.getName());
            }

            training.setUserName(user.getName());
        }

        return ApiResult.success(page);
    }


    @Log("查询我的证书")
    @GetMapping("/selResume")
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> selResume(@RequestHeader(value = TOKEN_TAG, required = false) String token){

        UserDO user = this.getClientUser(token);
        if (user == null){
            return ApiResult.invalid();
        }
        ResumesDO resumes = resumesService.findOneByKv("user_id" ,user.getId());
        Map map = new HashMap();
        if (resumes != null){
            if (resumes.getWorkExperience() != "" && !resumes.getWorkExperience().equals("") && resumes.getWorkYears() != null && !resumes.getWorkYears().equals("")
            && resumes.getNativePlace() != null && !resumes.getNativePlace().equals("") && resumes.getGraduatedFrom() != null && !resumes.getGraduatedFrom().equals("")
            && resumes.getDesiredOccupation() != "" && !resumes.getDesiredOccupation().equals("") && resumes.getExpectedSalary()!= null && resumes.getExpectedSalary().equals("")
            && resumes.getSelfEvaluation() != null && !resumes.getSelfEvaluation().equals("") && resumes.getEducationExperience() != null && !resumes.getEducationExperience().equals("")
            && resumes.getJobNature() != null && !resumes.getJobNature().equals("") && resumes.getApplyState() != null && !resumes.getApplyState().equals("")
            && resumes.getSkills() != null && !resumes.getSkills().equals("") && resumes.getProject() != null && resumes.getProject().equals("")
            && resumes.getJobAddress() != null && !resumes.getJobAddress().equals("")){
                map.put("state" , 0);
                return ApiResult.success(map);
            }else {
                map.put("state" , -1);
                return ApiResult.success(map);
            }

        }else {
            map.put("state" , -1);
            return ApiResult.success(map);
        }

    }


}
